<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2018/4/13
 * Time: 14:19
 */

namespace App\Http\Org;


use Yunpian\Sdk\YunpianClient;

class Message
{

    const ON_YUN_PIAN = 'YUNPIAN';


    /**
     * 发送短信验证码
     * @param $telephone
     * @param $code
     * @return bool
     */
    public static function sendCode($telephone, $code)
    {
        $on = getenv('MESSAGE_ON');
        if ($on == self::ON_YUN_PIAN) {
            $params = self::createParam($telephone, $code);
            return self::_yunpian($params);
        }
    }

    /**
     * 构建短信参数，code和text只选择一个，如果两个都填写，则发送code模板
     * @param $telephone    @手机号
     * @param null $code    @验证码
     * @param null $text    @短信内容
     * @return array
     */
    public static function createParam($telephone, $code=null, $text = null)
    {
        return array('telephone' => $telephone, 'code' => $code, 'text' => $text);
    }

    /**
     * 云片短信
     * @param $params
     * @return bool
     */
    private static function _yunpian($params)
    {

        $key = getenv('MESSAGE_KEY');

        $sendText   = '';
        $telephone  = $params['telephone'];
        $code       = $params['code'];
        $text       = $params['text'];

        if (empty($telephone)) return false;

        if (empty($text) && empty($code)) return false;

        $temp       = getenv('MESSAGE_TEMPLATE');

        if (!empty($code)) $sendText = self::_codeSendText($temp, $code);


        $p          = [YunpianClient::MOBILE => $telephone,YunpianClient::TEXT => $sendText];

        $client = YunpianClient::create($key);

        $r = $client->sms()->single_send($p);
        if ($r->isSucc()) {
            return true;
        }
        return false;
    }

    private static function _codeSendText($temp,$code)
    {
        return '【' . $temp . '】您的验证码是' . $code ;
    }

    private static function _sendText($temp, $text)
    {
        return '【' . $temp . '】' . $text ;
    }

}